package com.nvn.washiodriver.network.ws;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.nvn.washiodriver.Objects.OrderStatus;
import com.nvn.washiodriver.network.NetworkUtils;
import com.nvn.washiodriver.network.WebServiceCommunicatorListener;
import com.nvn.washiodriver.utils.Statics;

@SuppressLint("SimpleDateFormat")
public class GetStatusesListWSControl extends BaseWSControl {

	public GetStatusesListWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId) {
		super(context, listener, WebServiceFlag.GET_ORDER_STATUSES);

	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.WASHIO_WS_URL + "order/statuses";

		try {
			String respone = NetworkUtils.doRequest(url);
			try {
				JSONObject job = new JSONObject(respone);
				return getStatusFromJSONObject(Statics.getJSONArray(job, "orderStatuses"));

			} catch (JSONException e) {
				mError = e.getMessage();
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<OrderStatus> getStatusFromJSONObject(
			JSONArray jArray) throws JSONException {
		ArrayList<OrderStatus> statuses = new ArrayList<OrderStatus>();
		
		for (int i = 0; i < jArray.length(); i++) {
			JSONObject jStatus = jArray.getJSONObject(i);
			
			OrderStatus oStatus = new OrderStatus();
			oStatus.setObjectId(Statics.getString(jStatus, "id"));
			oStatus.setOrdinalValue(Statics.getString(jStatus, "ordinalValue"));
			oStatus.setOrdinalValueClient(Statics.getString(jStatus, "ordinalValueClient"));
			oStatus.setsClient(Statics.getString(jStatus, "statusClient"));
			oStatus.setsLookup(Statics.getString(jStatus, "statusLookup"));
			oStatus.setPickUp(Statics.getBoolean(jStatus, "isDriverPickup"));
			oStatus.setDropOff(Statics.getBoolean(jStatus, "isDriverDropoff"));
			oStatus.setStatus(Statics.getString(jStatus, "status"));
			
			statuses.add(oStatus);
		}
		
		return statuses;
	}
}
